define(function (require, exports, module) {
    var $ = require('jquery');


    var angular = require('angular');
    require('angular-ueditor');


    var material = angular.module('material',[
        'ngRoute',
        'direcitves.ueditor',
        'common',
        'directives',
        'services',
        'controllers'
    ]);

    require('./modules/common');
    require('./modules/directives/pagination');
    require('./modules/voice/voiceService');
    require('./modules/video/videoService');

    require('./modules/pictures/picturesController');
    require('./modules/voice/voiceController');
    require('./modules/video/videoController');
    require('./modules/video/videoDetailController');

    angular.module('services',[
        'material.voiceService',
        'material.videoService'
    ]);

    angular.module('directives',[
        'directives.menu',
        'directives.page'
    ]);

    angular.module('controllers',[
        'material.voiceController',
        'material.videoDetailController',
        'material.videoController'
    ]);


    material.config(function ($routeProvider) {
        $routeProvider
            .when('/material', {
                controller: 'imgText',
                templateUrl: "business_modules/material/ngviews/img_text.html"
            })
            .when('/material/img_text', {
                controller: 'imgText',
                templateUrl: "business_modules/material/ngviews/img_text.html"
            })
            .when('/material/img_text/edit', {
                controller: 'imgTextEdit',
                templateUrl: "business_modules/material/ngviews/img_text_edit.html"
            })
            .when('/material/img_text/edit/:id', {
                controller: 'imgTextEdit',
                templateUrl: "business_modules/material/ngviews/img_text_edit.html"
            })
            .when('/material/pictures', {
                controller: 'pictures',
                templateUrl: "business_modules/material/ngviews/pictures.html"
            })
            .when('/material/voice', {
                controller: 'voice',
                templateUrl: "business_modules/material/ngviews/voice.html"
            })
            .when('/material/video', {
                controller: 'video',
                templateUrl: "business_modules/material/ngviews/video.html"
            })
            .when('/material/video/detail/:videoId',{
                controller: 'videoDetail',
                templateUrl: "business_modules/material/ngviews/video_new.html"
            })
            .when('/material/video/new',{
                controller: 'videoDetail',
                templateUrl: "business_modules/material/ngviews/video_new.html"
            })
            .otherwise({
                redirectTo: '/material'
            });
    });
    material.directive('materialUl', ['$compile', '$document', function ($compile, $document) {
        return {
            restrict: 'A',
            replace: true,
            templateUrl: 'business_modules/material/ngviews/meterial_ul.html',
            link: function (scope, elm, attrs, ctl) {
                scope.activeLi = attrs.activeLi;
            }
        };
    }]);
    material.service('imgTextService',['http',function(http){
        var ret = {
            getList : function(options){
                var params = {
                    keyword : '',
                    limit : 10,
                    offset : 0
                };
                http.get('material/mpnews-list', $.extend(params,options.params))
                    .success(function(data, status, headers, config) {
                        if(data.retCode == 0){
                            options.success(data);
                        }
                    })

            },
            getImgText : function(options){
                var params = {
                    id : options.id
                };
                http.get('material/get-mpnews',params)
                    .success(function(data, status, headers, config) {
                        if(data.retCode == 0){
                            options.success(data);
                        }
                    })
            },
            saveImgText : function(options){
                http.post('material/save',options.data,options.id?{id : options.id}:{})
                    .success(function(data, status, headers, config) {
                        if(data.retCode == 0){
                            options.success(data);
                        }else if(data.retCode == -1){
                            alert(data.msg);
                        }
                        else{
                            alert('保存失败！');
                        }
                    })
            },
            deleteImgText : function(options){
                var params = {
                    id : options.id
                };
                http.get('material/del-mpnews',params)
                    .success(function(data, status, headers, config) {
                        if(data.retCode == 0){
                            options.success(data);
                        }
                    })
                    .error(function(data, status, headers, config) {

                    });
            }
        }
        return ret;
    }]);
    material.controller('imgText',['$scope','imgTextService',function($scope,imgTextService){
        $scope.limit = 10;
        $scope.pagination = {
            pages: 0,
            current: 1,
            change: function (page) {
                $scope.getList($scope.searchMsg,page);
            }
        };
        $scope.getList = function(keyword,page){
            imgTextService.getList({
                params : {
                    keyword : keyword,
                    limit : $scope.limit,
                    offset : $scope.limit * (page - 1)
                },
                success : function(data, status, headers, config) {
                    $scope.imgTexts = data.data;
                    $scope.pagination.pages = Math.ceil(data.data.total / $scope.limit);
                }
            });
        }

        $scope.searchMsg = '';

        $scope.viewType = 'card';

        $scope.changeView = function($event){
            var $targetElement = $($event.target);
            $scope.viewType = $targetElement.data('view');
        }

        $scope.clearMsg = function(){
            $scope.searchMsg = '';
            $scope.search();
        }

        $scope.search = function(){
            $scope.getList($scope.searchMsg,1);
        }

        $scope.deleteObj = {
            followType : 'text',
            title: "确定删除此素材吗？",
            text: function (index) {
                return '';
            },
            validate: function (text) {
                return true;
            },
            ok: function (name,id) {
                imgTextService.deleteImgText({
                    id : id,
                    success : function(data, status, headers, config) {
                        imgTextService.getList({
                            success : function(data, status, headers, config) {
                                $scope.imgTexts = data.data;
                            }
                        });
                    }
                })
            }
        };

        //初始化数据
        $scope.getList($scope.searchMsg,1);
    }])
    .controller('imgTextEdit',['$rootScope','$scope','$routeParams','imgTextService','picturesService','FileUploader','http','$timeout',
            function($rootScope,$scope,$routeParams,imgTextService,picturesService,FileUploader,http,$timeout){
        var emptyImgText = {
            'id' : '',
            "title": "",
            "author": "",
            "cover_url": "",
            'cover_name' : '',
            "is_cover_showin_body": "",
            "summary": "",
            "body": "",
            "original_url": ""
        };

        $scope.$on('formValidCallback', function(event,data) {
            if(data===true){
                $scope.formValidLength -=1;
            }
            if($scope.formValidLength==0){
                imgTextService.saveImgText({
                    id : $scope.imgText.id,
                    data : {
                        data : angular.copy($scope.imgText.articles),
                        type : 'news'
                    },
                    success : function(data, status, headers, config) {
                        if($scope.massFlag){
                            var media_id = $scope.imgText.media_id || data.data.media_id;
                            http.post('mass-message/send',{
                                msg_type: "mpnews",
                                content: media_id
                            })
                            .success(function (res) {
                                if (res.result || res.retCode === 0) {
                                    $rootScope.$emit('httpRequestSuccess','发送成功');
                                    location.hash = '/material';
                                    return;
                                }
                                $rootScope.$emit('httpRequestFail','群发图文消息失败');
                            })
                            .error(function (res) {
                                $rootScope.$emit('httpRequestFail','群发图文消息失败');
                            });
                        }else{
                            location.hash = '/material';
                        }
                    }
                })
            }

        });
        $scope.id = $routeParams.id || 0;

        $scope.imgText = {};

        $scope.currArticleIndex = 0;

        $scope.addImage = function(url,name){
            $scope.imgText['articles'][$scope.currArticleIndex].cover_url = url;
            $scope.imgText['articles'][$scope.currArticleIndex].cover_name = name;
        }


        $scope.addArticle =function(){
            var imgText = $scope.imgText;
            imgText.articles.push(angular.copy(emptyImgText));
            $scope.currArticleIndex = imgText.articles.length - 1;
            $timeout(
                function() {
                    $($('.form-content').get($scope.currArticleIndex))
                        .css('margin-top', $('.imgtext:last').position().top);
                },0);
        }



        $scope.changeActicle = function(index,$event) {
            $scope.currArticleIndex = index;
            $($('.form-content').get(index)).css('margin-top',$($event.target).closest('.imgtext').position().top);
        }

        $scope.deleteActicle = function(index,$event) {
            $scope.imgText.articles.splice(index, 1);
            $scope.currArticleIndex = 0;
        }
        $scope.addOrUpdateImgText = function(massFlag){
            $scope.massFlag =massFlag;//群发标志位
            $scope.formValidLength = $scope.imgText.articles.length;
            $scope.$broadcast('formValid');
        }

        $scope.changeIsCoverShowinBody = function(){
            var acticle = $scope.imgText['articles'][$scope.currArticleIndex];
            if(acticle.is_cover_showin_body === '0'){
                acticle.is_cover_showin_body = '1';
            }else{
                acticle.is_cover_showin_body = '0';
            }
        }

        $scope.uploaderOptions = {
            success : function(res){
                $scope.addImage(res.original,res.imgname);
            }
        }

        $scope.showImages = function($dialogScope){
            $dialogScope.pictures = picturesService;
            $dialogScope.selPictureId = '';
            $dialogScope.changeSelPictureId = function(id){
                $dialogScope.selPictureId = id;
            }

            //加载图片库
            $dialogScope.pictures.getGroup();
        }

        $scope.okImages = function($dialogScope){
            var picture = $dialogScope.pictures.getPictureById($dialogScope.selPictureId);
            if(picture){
                $scope.addImage(picture.img_url,picture.name);
            }

        }
        $scope.okUeditorImages = function($dialogScope){
            var picture = $dialogScope.pictures.getPictureById($dialogScope.selPictureId);
            if(picture){
                $scope.$broadcast('addImage',picture);
            }

        }


        if($scope.id !== 0){
            $scope.handleType = 'update';
            imgTextService.getImgText({
                id : $scope.id,
                success : function(data, status, headers, config) {
                    $scope.imgText = data.data;
                }
            });
        }else {
            $scope.handleType = 'add';
            $scope.imgText.articles =[angular.copy(emptyImgText)];

        }
    }])
    .controller('articleController',['$scope',function($scope){
            $scope.$on('formValid', function(event,data) {
                if($scope.imgTextForm){
                    $scope.imgTextForm.$setSubmitted(true);
                    if($scope.imgTextForm.$invalid || !$scope.article.cover_url || !$scope.article.body){
                        $scope.$emit('formValidCallback',false);
                    }else{
                        $scope.$emit('formValidCallback',true);
                    }
                }
            });
        }])
});
